<script setup>
import LayoutNav from '../Layout/components/LayoutNav.vue';
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import Question from './components/Question.vue';
import { ref,watch,onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router' // 确保引入useRouter
import { getGoodByIdAPI,getSkuListAPI } from '@/api/good'
import { useTokenStore } from '@/store/token'

// 获取登录用户信息
const tokenStore = useTokenStore();
const userIdentity = tokenStore.user.identity

const router = useRouter() // 获取router实例
//商品详情页标签
const activeName = ref('first')

//获取商品细节
const goods = ref({})
const route = useRoute()
console.log(route.params);

const getGoodDetail = async () => {
  const res = await getGoodByIdAPI(route.params.goodId)
  goods.value = res.data
  checkInfo.value.goodId = goods.value.goodId
  checkInfo.value.goodName = goods.value.goodName
  checkInfo.value.price = goods.value.price
}
getGoodDetail()

//获取商品评论
import { getCommentListAPI } from '@/api/good'
const commentList = ref([])
const pageList = ref([]); // 当前页的数据（用于显示）

const getCommentList = async () => {
  const res = await getCommentListAPI({goodId: route.params.goodId})
  // 过滤掉全是 null 的评论对象
  commentList.value = res.data.filter(comment => 
    // 检查是否至少有一个属性不为 null
    comment && Object.values(comment).some(value => value.commentId !== null)
  )
  total.value = commentList.value.length
  pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
  updatePaginatedList();   // 更新分页数据
}


//分页
const total = ref(0); // 总条数
const pagePages = ref(1); // 总页数
const currentPage = ref(1); // 当前页码
const pageSize = ref(5);  // 每页显示条数

// 更新分页数据（根据 currentPage 和 pageSize）
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pageList.value = commentList.value.slice(start, end);  // 切割出当前页的数据
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

const skuData = ref({
  colors: [],
  sizes: [],
  skuList: []
})
//获取商品规格
const getSkuList = async () => {
  const res = await getSkuListAPI(route.params.goodId)
  console.log(res.data)
  skuData.value = transformSkuData(res.data)
  console.log(skuData.value)
}

const transformSkuData = (originalData) => {
  // 创建新对象而不是直接修改 skuData.value
  const result = {
    colors: [],
    sizes: [],
    skuList: []
  }

  // 提取唯一的颜色和尺码
  const uniqueColors = new Set()
  const uniqueSizes = new Set()

  originalData.forEach(item => {
    uniqueColors.add(item.color)
    uniqueSizes.add(item.size)
  })

  // 处理颜色数据
  result.colors = Array.from(uniqueColors).map(color => {
    const imageItem = originalData.find(item => item.color === color)
    return {
      name: color,
      image: imageItem?.image || ''
    }
  })

  // 处理尺码数据
  result.sizes = Array.from(uniqueSizes)

  // 处理SKU列表
  result.skuList = originalData.map(item => ({
    skuId: item.sku_id,
    color: item.color,
    size: item.size,
    quantity: item.quantity
  }))

  return result  // 返回转换后的数据
}



const checkInfo = ref({
  goodId: '',
  goodName: '',
  salerId: route.params.userId, 
  salerName: route.params.storeName,
  price: '',
  quantity: 1,
  totalPrice: 0,
  selectedSku: {
    skuId: '',
    color: '',
    size: '',
    image: ''
  },
})
// 监听数量和价格变化，自动计算总价
watch(
  [
    () => checkInfo.value.quantity,
    () => checkInfo.value.price
  ],
  () => {
    checkInfo.value.totalPrice = checkInfo.value.price * checkInfo.value.quantity
  },
  { immediate: true } // 立即执行一次
)
import { useOrderStore } from '@/store/order';
import { ElMessage } from 'element-plus';
const orderStore = useOrderStore();
//立即购买
const handleSubmit = async () => {
  console.log(checkInfo.value);
  if (!checkInfo.value.selectedSku.color || !checkInfo.value.selectedSku.size){
    ElMessage.error('请选择商品规格')
    return
  }
  orderStore.setCheckInfo(checkInfo.value);
  router.push('/order')
}

// 确保在组件挂载时调用
onMounted(() => {
  getCommentList()
  getSkuList()

})
</script>

<template>
    <LayoutNav/>
    <div class="container">
        <div class="header-box">
        <div class="logo">
        <RouterLink to="/">桃禧</RouterLink>
        </div>
        <p>商品浏览</p>
      </div>
    </div>

    <div class="goods-page">
    <div class="container" v-if="goods">
      <el-empty v-if="!goods.goodId" description="暂无商品信息" />
      <template v-else>
      <!-- 客服咨询 -->
      <div v-if="userIdentity != '0'" class="other-container">
        <router-link to="/custermer" class="btn">
          定制商品联系客服
        </router-link >
        <router-link :to="{name: 'launchCrowdFunding', params: {goodId: goods.goodId}}" class="btn">
          众筹定制
        </router-link >
      </div>
      <!-- 商品信息 -->
      <div class="info-container">
        <div>
          <div class="goods-info">
            <div class="media">
              <!-- 图片预览区 -->
              <img class="goods-img" :src="goods.images" alt="" />
            </div>
            <div class="spec">
              <!-- 商品信息区 -->
              <p class="g-name"> {{ goods.goodName }} </p>
              <p class="g-desc">{{ goods.description }} </p>
              <p class="g-price">
                <span>{{ goods.price }}</span>
              </p>
              <el-empty v-if="!skuData.colors.length" description="暂无规格信息" />
              <template v-else>
                <Sku
                  :sku-data="skuData"
                  v-model:sku="checkInfo.selectedSku"
                  v-model:quantity="checkInfo.quantity"
                />
                <!-- 按钮组件 -->
                <div>
                  <el-button size="large" class="btn" type="primary" @click="handleSubmit">
                    立即购买
                  </el-button>
                </div>
              </template>
            </div>
          </div>
          <div class="goods-footer">
            <div class="goods-article">
              <!-- 商品详情 -->
              <div class="goods-tabs">
                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                  <el-tab-pane label="商品详情" name="first">
                  <div class="goods-detail">
                    <el-empty v-if="!skuData.colors.length" description="暂无规格信息" />
                    <template v-else>
                      <ul class="attrs">
                        <li class="attr-item">
                          <span class="dt">颜色：</span>
                          <span class="dd">
                            <template v-for="(item, index) in skuData.colors" :key="item.name">
                              {{ item.name }}{{ index !== skuData.colors.length - 1 ? '、' : '' }}
                            </template>
                          </span>
                        </li>
                        <li class="attr-item">
                          <span class="dt">尺寸：</span>
                          <span class="dd">
                            <template v-for="(item, index) in skuData.sizes" :key="item">
                              {{ item }}{{ index !== skuData.sizes.length - 1 ? '、' : '' }}
                            </template>
                          </span>
                        </li>
                      </ul>
                      <img v-for="item in skuData.colors" :src="item.image" :key="item" alt="">
                    </template>
                  </div>
                  </el-tab-pane>
                  <el-tab-pane label="商品评价" name="second">
                    <div class="good-commont">
                    <div class="commont-head">
                      <h1>所有评价</h1>
                      <ul>
                        <li>共计{{ total }}条评论</li>
                      </ul>
                    </div>

                    <el-empty v-if="!commentList.length" description="暂无评论" />
  
                    <template v-else>
                      <div class="commont-item">
                        <ul>
                          <li v-for="comment in pageList" :key="comment.commentId">
                            <div class="commont-box"  v-if="comment.commentId!=null">
                              <el-avatar class="avater" :size="50" :src="comment.user.avatar" />
                              <div class="main">
                                <div class="header"><p>{{ comment.user.username }}</p></div>
                                <div class="content"><p>{{ comment.content }}</p></div>
                                <div class="footer">
                                  <p>{{ comment.date }}</p>
                                  <el-rate v-model="comment.rating" disabled/>
                                </div>
                              </div>
                            </div>
                          </li>
                        </ul>
                      </div>
                      <!--分页区域-->
                      <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :page-sizes="[5]"
                            :small="small"
                            :disabled="disabled"
                            :background="background"
                            layout="sizes,prev, pager, next, jumper"
                            :total="total"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            style="position: absolute ;bottom: 30px; margin-top: 30px; margin-left: 20%;"
                        />
                    </template>
                  </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
            <!-- 常见问题 -->
            <div class="goods-aside">
              <Question/>
            </div>
          </div>
        </div>
      </div>
      </template>
    </div>
  </div>
    <LayoutFooter/>
</template>

<style scoped lang='scss'>
.header-box{
    background: #fff;
    position: relative;
    height: 120px;
    border-bottom:1px solid #ccc;
    display: flex;
    p{
      font-size: 24px;
      margin-left: 20px;
      margin-top: 50px;
    }
    .logo {
    margin-left: 50px;
    width: 80px;

    a {
      display: block;
      height: 100px;
      width: 100%;
      text-indent: -9999px;
      background: url('@/assets/images/logo.png') no-repeat center 18px / contain;
    }
  }
  .search-box{
    position: absolute;
    display: flex;
    justify-content: center;
    top: 50%;
    right:50px;
    .el-input {
        margin-left: 20px;
    }
    .el-button{
        margin-left: 20px;
    }
  }
}
    .container{
      background-color: #fff;
    }

    .goods-page {
  .goods-info {
    min-height: 480px;
    background: #fff;
    display: flex;

    .media {
      width: 580px;
      height: 480px;
      padding: 30px 50px;
      .goods-img{
        width: 480px;
        height: 400px;
        object-fit: cover;
      }
    }

    .spec {
      flex: 1;
      padding: 30px 30px 30px 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;

    .goods-article {
      width: 940px;
      margin-right: 20px;
    }

    .goods-aside {
      width: 280px;
      min-height: 1000px;
      border-radius: 5px;
      padding: 10px;
    }
  }

  .goods-tabs {
    min-height: 600px;
    background: #fff;
  }

  // ::v-deep .el-tabs__nav{
  //   width: 180px;
  // }
    /* 内容文字 */
  :v-deep .el-tabs__item {
    padding: 20px !important; //内容与padding框的距离
    margin-right: 20px;
    font-size: 20px !important; //更改选项卡标签的字体大小
  }

  .goods-warn {
    min-height: 600px;
    background: #fff;
    margin-top: 20px;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {
    margin-top: 10px;

    span {
      &::before {
        content: "¥";
        font-size: 14px;
      }

      &:first-child {
        color: $priceColor;
        margin-right: 10px;
        font-size: 22px;
      }
    }
  }

  .goods-sales {
    display: flex;
    width: 400px;
    align-items: center;
    text-align: center;
    height: 140px;

    li {
      flex: 1;
      position: relative;

      ~li::after {
        position: absolute;
        top: 10px;
        left: 0;
        height: 60px;
        border-left: 1px solid #e4e4e4;
        content: "";
      }

      p {
        &:first-child {
          color: #999;
        }

        &:nth-child(2) {
          color: $priceColor;
          margin-top: 10px;
        }

        &:last-child {
          color: #666;
          margin-top: 10px;

          i {
            color: $xtxColor;
            font-size: 14px;
            margin-right: 2px;
          }

          &:hover {
            color: $xtxColor;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.goods-tabs {
  min-height: 600px;
  background: #fff;

  nav {
    height: 70px;
    line-height: 70px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      >span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  padding: 40px;

  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }

  >img {
    width: 100%;
  }
}

.good-commont{
  position: relative;
  width: 940px;
  margin-right: 20px;
  min-height: 1000px;

  .commont-head{
    h1{
      padding: 20px 0 0 20px;
    }
    ul{
      padding: 20px 0 10px 10px;
      margin-left: 10px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e0e0e0;


      li{
        font-size: 18px;
        margin-right: 40px;
      }
    }
    
  }

  .commont-item{
    ul{
      li{
        height: 150px;
        border-bottom: 1px solid #e0e0e0;
      }
    }
    .commont-box{
        display: flex;
        align-items: center;
        padding: 10px 0 0 30px;
        height: 150px;
    }

    .avater{
      width: 50px;
      height: 50px;
      margin-bottom: 50px;
      border-radius: 50%;
    }
    .main{
      margin-left: 30px;
    }
    .header p {
      font-size: 20px;
      font-weight: bold;
    }

    .content p {
        font-size: 18px;
        padding: 10px 0 10px 0px;
        color: #666;
      }

    .footer {
        font-size: 15px;
        color: #999;
        display: flex;
        align-items: center;
      .el-rate{
        margin-left: 20px ;
      }
      }
  }
  .el-pagination{
    position: absolute;
    padding: 10px;
    bottom: 0;
  }
}

.btn {
  margin-top: 20px;

}

.bread-container {
  padding: 25px 0;
}

.container{
  position:relative;
}
.other-container{
  position: absolute;
  right: 20px;
  top: 100px;
  font-size: 16px;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  gap: 10px; /* 间距 */
  .btn{
    margin-top: 5px;
    width: 60px;
    height: 120px;    
    border-radius: 8px;
    padding: 5px;
    opacity: 1;
    color: #fff;
    background: rgba(229, 134, 134, 0.66);
    transition: all .5s;
    text-align: center;

    &:hover {
      transform: translate3d(0, -3px, 0);
      box-shadow: 0 3px 8px rgb(0 0 0 / 20%);
  }
  }
}

.good-image{
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
}
</style>